package 数据结构;

public class LeetCode59_螺旋矩阵 {
    public int[][] generateMatrix(int n) {
        int num = 1,tar = n* n;
        int[][] matrix = new int[n][n];
        int left = 0,right = n-1,top = 0,bottom = n-1;
        while(num <= tar) {
            // 第一行
            for(int i = left; i <= right; i++) {
                matrix[top][i] = num;
                num++;
            }
            // 最后一列
            for(int i = top+1; i <= bottom; i++) {
                matrix[i][right] = num;
                num++;
            }
            // 最后一行
            if(left < right && top < bottom) {
                for(int i = right-1; i > left; i--) {
                    matrix[bottom][i] = num;
                    num++;
                }
                // 第一列
                for(int i = bottom; i > top; i--) {
                    matrix[i][left] = num;
                    num++;
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return matrix;
    }

    public int[][] generateMatrix3(int n) {
        int l = 0, r = n - 1, t = 0, b = n - 1;
        int[][] mat = new int[n][n];
        int num = 1, tar = n * n;
        while(num <= tar){
            for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
            t++;
            for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
            r--;
            for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
            b--;
            for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
            l++;
        }
        return mat;
    }

    public int[][] generateMatrix2(int n) {
        int num = 1;
        int[][] matrix = new int[n][n];
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                matrix[top][column] = num;
                num++;
            }
            for (int row = top + 1; row <= bottom; row++) {
                matrix[row][right] = num;
                num++;
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    matrix[bottom][column] = num;
                    num++;
                }
                for (int row = bottom; row > top; row--) {
                    matrix[row][left] = num;
                    num++;
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return matrix;
    }

}
